<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>4_getSnapshotBeforeUpdate应用场景</title>
    <script
      crossorigin
      src="https://unpkg.com/react@18/umd/react.development.js"
    ></script>
    <script
      crossorigin
      src="https://unpkg.com/react-dom@18/umd/react-dom.development.js"
    ></script>
    <script src="../React-js//babel.min.js"></script>
    <style>
      @import 'https://unpkg.com/open-props@1.5.0/open-props.min.css';
      @import 'https://unpkg.com/open-props/normalize.min.css';
      body {
        display: flex;
        align-items: center;
        justify-content: center;
        height: 100vh;
        background-color: var(--gray-7);
      }
      .list {
        width: 200px;
        height: 150px;
        overflow: auto;
        border: 1px solid var(--indigo-7);
      }
      .news {
        height: 30px;
        border: 1px solid var(--purple-3);
      }
    </style>
  </head>
  <body>
    <!-- 容器 -->
    <div id="root"></div>

    <script type="text/babel">
      class NewList extends React.Component {
        state = { newArr: [] };

        componentDidMount() {
          setInterval(() => {
            // 获取原状态
            const { newArr } = this.state;
            // 模拟一条新闻
            const news = '新闻' + (newArr.length + 1);
            // 更新状态
            this.setState({ newArr: [news, ...newArr] });
          }, 1000);
        }

        getSnapshotBeforeUpdate() {
          return this.refs.list.scrollHeight; //未更新前的 总高度
        }

        componentDidUpdate(prevProps, prevState, height) {
          this.refs.list.scrollTop += this.refs.list.scrollHeight - height;
        }

        render() {
          return (
            <div className="list" ref="list">
              {this.state.newArr.map((item, index) => {
                return (
                  <div key={index} className="news">
                    {item}
                  </div>
                );
              })}
            </div>
          );
        }
      }

      const root = ReactDOM.createRoot(document.getElementById('root'));
      root.render(<NewList />);
    </script>
  </body>
</html>
